package com.example.userservice.service.impl;

import com.example.userservice.dto.LoginDTO;
import com.example.userservice.dto.OperationLogDTO;
import com.example.userservice.feign.UserServiceFeignClient;
import com.example.userservice.dto.RegisterDTO;
import com.example.userservice.feign.UserServiceFeignClient2;
//import com.example.userservice.service.LogProducer;
import com.example.userservice.logger.BizLogger;
import com.example.userservice.service.UserMapper;
import com.example.userservice.service.UserService;
import com.example.userservice.user.User;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.security.Keys;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

@Service
public class UserServiceImp implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private UserServiceFeignClient userServiceFeign;
    @Autowired
    private UserServiceFeignClient2 userServiceFeign2;

//    @Autowired
//    private LogProducer logProducer;
    @Override
    @Transactional
    public void register(RegisterDTO register) {
        //创建用户实体
        User user = new User();
        user.setUsername(register.getUsername());
        user.setPassword(register.getPassword());
        user.setEmail(register.getEmail());
        user.setPhone(register.getPhone());
        //数据库插入用户
        int insert_number = userMapper.insert(user);
        // RPC调用角色服务
        userServiceFeign.bindDefaultRole(user.getUser_id());

        OperationLogDTO log = new OperationLogDTO();
        log.setUserId(user.getUser_id());
        log.setAction("register");
        log.setIp("127.0.0.1");
        log.setDetail(register.getUsername()+" register success");
        userServiceFeign2.insert(log);
        //logProducer.sendLog(log);

        BizLogger.log("user", user.getUser_id(), "register", true, "register success");
    }

    private static final String SECRET_KEY = "test-secret-key-1234567890-abcdefghijk";
    @Override
    public String login(LoginDTO login) {
        Long userId = userMapper.selectUserId(login.getUsername());
        OperationLogDTO log = new OperationLogDTO();
        log.setUserId(userId);
        log.setAction("register");
        log.setIp("127.0.0.1");
        log.setDetail(login.getUsername()+" login success");
        userServiceFeign2.insert(log);

        return Jwts.builder()
                .setSubject(login.getUsername())
                .signWith(Keys.hmacShaKeyFor(SECRET_KEY.getBytes()))
                .compact()+"\nusername为"+login.getUsername();
    }

    @Override
    public List<String> getUsers(Long userId) {
        String username = userMapper.selectUsername(userId).get(0);
        OperationLogDTO log = new OperationLogDTO();
        log.setUserId(userId);
        log.setAction("getUsers");
        log.setIp("127.0.0.1");
        log.setDetail(username+" 查询用户表");
        userServiceFeign2.insert(log);

        int roleId = userMapper.selectRoleId(userId);
        if (roleId == 3) {
            return new ArrayList<>(userMapper.selectUsername(userId));
        }
        else return new ArrayList<>(userMapper.select(userId));
    }

    @Override
    public List<User> select(Long userId) {
        String username = userMapper.selectUsername(userId).get(0);
        int roleId = userMapper.selectRoleId(userId);
        OperationLogDTO log = new OperationLogDTO();
        log.setUserId(userId);
        log.setAction("select");
        log.setIp("127.0.0.1");
        log.setDetail(username+" 查询用户信息");
        userServiceFeign2.insert(log);

        if (roleId == 3) {
            return userMapper.selectSelf(userId);
        }
        return userMapper.selectAll(userId);
    }

    @Override
    public int change(Long userId,User user) {
        String username = userMapper.selectUsername(userId).get(0);
        int roleId = userMapper.selectRoleId(userId);

        int roleId1 = userMapper.selectRoleId(userId);
        int roleId2 = userMapper.selectRoleId(user.getUser_id());
        if (roleId1 > roleId2){
            return 0;
        }else{
            if (user.getPhone() != null) userMapper.changephone(userId,user);
            if (user.getEmail() != null) userMapper.changeemail(userId,user);
            OperationLogDTO log = new OperationLogDTO();
            log.setUserId(userId);
            log.setAction("change");
            log.setIp("127.0.0.1");
            if (roleId==1) log.setDetail("超管"+username+"修改用户id为"+user.getUser_id()+"的信息");
            else if (roleId==2) log.setDetail("管理员"+username+"修改用户id为"+user.getUser_id()+"的信息");
            else log.setDetail("用户"+username+"修改自己的信息");
            userServiceFeign2.insert(log);
            BizLogger.log("user", userId, "change", true, "change success");
            return 1;
        }
    }

    @Override
    public void resetPassword(Long userId) {
        String username = userMapper.selectUsername(userId).get(0);
        int roleId = userMapper.selectRoleId(userId);
        OperationLogDTO log = new OperationLogDTO();
        log.setUserId(userId);
        log.setAction("getUsers");
        log.setIp("127.0.0.1");
        if (roleId==1) log.setDetail("超管"+username+"重置所有用户密码");
        else if (roleId==2) log.setDetail("管理员"+username+"重置所有普通用户密码");
        else log.setDetail("用户"+username+"重置密码");
        userServiceFeign2.insert(log);

        BizLogger.log("user", userId, "resetPassword", true, "resetPassword success");

        if (roleId == 3){
            userMapper.resetPassword(userId);
        }
        userMapper.reset(userId);
    }
    @Override
    public int grade(Long userId,Long targetId) {
        int roleId = userMapper.selectRoleId(userId);
        if (roleId != 1) {
            return 0;
        }else {
            int roleId1 = userMapper.selectRoleId(targetId);
            String username = userMapper.selectUsername(targetId).get(0);
            OperationLogDTO log = new OperationLogDTO();
            log.setUserId(userId);
            log.setAction("grade");
            log.setIp("127.0.0.1");
            if (roleId1 == 2) {
                userServiceFeign.downgradeToUser(targetId);
                log.setDetail("超管把用户"+username+"修改为普通用户");
            } else {
                userServiceFeign.upgradeToAdmin(targetId);
                log.setDetail("超管把用户"+username+"修改为管理员");
            }
            userServiceFeign2.insert(log);
            BizLogger.log("user", userId, "grade_change", true, "change success");
            return 1;
        }
    }
}
